package android.pot.com.smartcar.ui.home.activity;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.pot.com.smartcar.BaiduMapActivity;
import android.pot.com.smartcar.R;
import android.pot.com.smartcar.action.Action;
import android.pot.com.smartcar.base.CommonAdapter;
import android.pot.com.smartcar.base.MyResponseHandler;
import android.pot.com.smartcar.base.ViewHolder;
import android.pot.com.smartcar.base.swipe.SwipeBackActivity;
import android.pot.com.smartcar.config.MyConfig;
import android.pot.com.smartcar.entity.ShopDetailEntity;
import android.pot.com.smartcar.fragment.CallDialogView;
import android.pot.com.smartcar.tool.LoadingTool;
import android.pot.com.smartcar.tool.TipToast;
import android.pot.com.smartcar.ui.home.BGABannerssAdapter;
import android.pot.com.smartcar.util.GsonUtil;
import android.pot.com.smartcar.util.PermissionUtil;
import android.pot.com.smartcar.util.TextCheckUtil;
import android.pot.com.smartcar.widget.ListViewForScrollView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bingoogolapple.bgabanner.BGABanner;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by zhaoshilu on 2017/11/27.
 */
public class ShopDetailActivity extends SwipeBackActivity implements EasyPermissions.PermissionCallbacks{

    private CommonAdapter adapter;

    private ArrayList<String> imgList = new ArrayList<>();

    private ImageView iv_collect;

    private BGABanner mStackBanner;

    private String shop_id;

    private String phone_number;

    //地图传递的值
    private String lng;

    private String lat;

    private List<ShopDetailEntity.ServiceItem> serviceList = new ArrayList<>();

    private CommonAdapter  mAdapter;

    private TextView tv_shop_name,tv_identify,tv_business_hours,tv_shop_address,tv_phone;

    private ShopDetailEntity entity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shops_detail);
        initView();
        addListener();
        initData();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mStackBanner!=null){
            mStackBanner.startAutoPlay();
        }

    }

    @Override
    public void onPause() {
        super.onPause();

        if (mStackBanner!=null) {
            mStackBanner.stopAutoPlay();
        }
    }


    @Override
    protected void initView() {
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("店铺详情");
        iv_collect = (ImageView) findViewById(R.id.iv_collect);
        tv_shop_name = (TextView) findViewById(R.id.tv_shop_name);
        tv_identify = (TextView) findViewById(R.id.tv_identify);
        tv_business_hours = (TextView) findViewById(R.id.tv_business_hours);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        tv_shop_address = (TextView) findViewById(R.id.tv_shop_address);
        initListView();
        initBannerView();
    }

    private void initListView(){
        ListViewForScrollView listViewForScrollView = (ListViewForScrollView) findViewById(R.id.lv_list);
        mAdapter = new CommonAdapter<ShopDetailEntity.ServiceItem>(this,serviceList,R.layout.listcell_product_detail) {
            @Override
            public void convert(ViewHolder helper, ShopDetailEntity.ServiceItem item) {
                helper.setText(R.id.tv_item_name,item.getItems());
                try {
                    Double.parseDouble(item.getMoney());
                    helper.setVisibility(R.id.tv_symbol,View.VISIBLE);
                }catch (Exception e){
                    helper.setVisibility(R.id.tv_symbol,View.GONE);
                }
                helper.setText(R.id.tv_price,formate2Money(item.getMoney()));

            }
        };
        listViewForScrollView.setAdapter(mAdapter);

    }

    private String formate2Money(String str){
        if (str == null||str.length() == 0){
            return "0.00";
        }else{
            try {
                BigDecimal bigDecimal = new BigDecimal(str);
                BigDecimal num = bigDecimal.setScale(2,BigDecimal.ROUND_DOWN);
                return num.toString();
            }catch (Exception e){
                return str;
            }

        }
    }

    private void initBannerView() {
        mStackBanner = (BGABanner) findViewById(R.id.home_kanner);
        mStackBanner.setAdapter(new BGABannerssAdapter(this));

        mStackBanner.setDelegate(new BGABanner.Delegate<ImageView, String>() {
            @Override
            public void onBannerItemClick(BGABanner banner, ImageView itemView, String model, int position) {
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("img", imgList);
                bundle.putInt("CurPic",position);
                startAct(ShopDetailActivity.this, PhotosScanActivity.class, bundle);
            }
        });
    }


    @Override
    protected void addListener() {
        findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToFinishActivity();
            }
        });
        findViewById(R.id.iv_collect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                collection();
            }
        });
        findViewById(R.id.rl_phone).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null !=entity){
                    if (!TextUtils.isEmpty(entity.getShop_phone())){
                        CallDialogView dialogView = new CallDialogView(ShopDetailActivity.this,entity.getShop_phone(),"call");
                        dialogView.show(getSupportFragmentManager(),"dialogView");
                        dialogView.setMethodClickListener(new CallDialogView.OnMethodClickListener() {
                            @Override
                            public void methodClick( ) {
                                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + entity.getShop_phone()));
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            }
                        });
                    }else {
                        TipToast.show("暂无商家电话");
                    }
                }

            }
        });
        findViewById(R.id.rl_map).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LocationTask();
            }
        });


    }

    @Override
    protected void initData() {
        Bundle bundle =  getIntent().getExtras();
        shop_id= bundle.getString("shop_id");

        getDetailData();
    }


    private void getDetailData(){
        Map<String,String> params = new HashMap<>();
        params.put("shop_id",shop_id+"");
        LoadingTool.StartLoading(this);
        Action.get().shop_details(this, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message,JSONObject response) {
                LoadingTool.EndLoading(ShopDetailActivity.this);
                entity =  GsonUtil.getObject(response.toString(), ShopDetailEntity.class);
                serviceList.addAll(entity.getService_items());
                mAdapter.notifyDataSetChanged();

                if (entity.getCollection_status() == 1) {
                    iv_collect.setImageResource(R.mipmap.img_collection);
                }else {
                    iv_collect.setImageResource(R.mipmap.img_uncollection);
                }
                 tv_shop_name.setText(TextCheckUtil.CheckString(entity.getShop_name()));
                tv_business_hours.setText("营业时间："+TextCheckUtil.CheckString(entity.getBusiness_hours()));
                tv_phone.setText("电话："+TextCheckUtil.CheckString(entity.getShop_phone()));
                tv_shop_address.setText(TextCheckUtil.CheckString(entity.getShop_address()));
                if (entity.getCertification_status() == 1){
                    tv_identify.setVisibility(View.VISIBLE);
                }else{
                    tv_identify.setVisibility(View.GONE);
                }
                lat = entity.getLatitude();
                lng =entity.getLongitude();
                if (null != entity.getDetails_map()) {
                    for (String str : entity.getDetails_map()) {
                        imgList.add(MyConfig.IMG_URL + str);
                    }
                }
                mStackBanner.setData(imgList,null);
            }
        });
    }

    private void collection(){
        Map<String,String> params = new HashMap<>();
        params.put("shop_id",shop_id+"");
        LoadingTool.StartLoading(this);
        Action.get().collection(this, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message,JSONObject response) {
                LoadingTool.EndLoading(ShopDetailActivity.this);
                int status = 0;
                try {
                    status = response.getInt("status");
                    if (status== 1) {
                        iv_collect.setImageResource(R.mipmap.img_collection);
                    }else {
                        iv_collect.setImageResource(R.mipmap.img_uncollection);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_LOCATION_PERM) {

        }
    }


    /**
     * 请求位置权限码
     */
    public static final int REQUEST_LOCATION_PERM = 101;

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            PermissionUtil.openPermissionDialog(this,"智慧养车需要申请位置权限,请打开设置页面去申请");
        }
    }

    /**
     * EsayPermissions接管权限处理逻辑
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @AfterPermissionGranted(REQUEST_LOCATION_PERM)
    public void LocationTask() {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
            // Have permission, do the thing!
            if (TextUtils.isEmpty(lat)||TextUtils.isEmpty(lng)){
                TipToast.show("商户位置不准确");
                return;
            }
            Bundle bundle = new Bundle();
            String remark = lng+","+lat;
            bundle.putString("latLng",remark);
            bundle.putString("name",TextCheckUtil.CheckString(entity.getShop_name()));
            bundle.putString("address",TextCheckUtil.CheckString(entity.getShop_address()));
            startAct(this,BaiduMapActivity.class,bundle);
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, "需要请求获取位置权限",
                    REQUEST_LOCATION_PERM, Manifest.permission.ACCESS_COARSE_LOCATION);
        }
    }
}